package com.rrs.client

import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.util.Log
import android.view.ViewGroup
import android.widget.Toast
import com.google.gson.GsonBuilder
import kotlinx.coroutines.CoroutineExceptionHandler
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.reflect.Type
import androidx.core.content.edit

const val fromCloud = 0
const val fromLocal = 1

class MList<T> {
    lateinit var list: ArrayList<T>
}

class Response<T> {
    lateinit var list: ArrayList<T>
    var source = fromCloud
}

class Utils(private val context: Context) {
    val globalScopeErrorHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
        Log.d("MicroParking", throwable.printStackTrace().toString())
    }

    // Apr 16, 2025, 5:35:54 PM
    val dateFormat = "MMM d, yyyy, hh:mm:ss aa"

    val sharedPreferences =
        context.getSharedPreferences("listCache", MODE_PRIVATE)

    /**
     * 从云端获取对象列表
     * @param client okhttp3客户端
     * @param url 云端url
     * @param type 要获取的对象的TypeToken类型
     * @param listName 列表名称，用于本地缓存的唯一标识符
     * @param isListFromCloud 从云端接收的数据是否为列表
     * @return 对象列表
     */
    fun <T> getObjsFromCloud(
        client: OkHttpClient,
        url: String,
        type: Type,
        listName: String,
        isListFromCloud: Boolean
    ): Response<T> {

        val response = Response<T>()

        val request: Request = Request.Builder()
            .url(url)
            .build()

        val gson = GsonBuilder()
            .disableHtmlEscaping()
            .setDateFormat(dateFormat)
            .create()

        try {
            client.newCall(request).execute().use { res ->
                val resBody = res.body?.string().toString()

                // 手动添加key
                val sb = StringBuilder(resBody)
                if (isListFromCloud) {
                    sb.insert(0, "{\"list\":")
                    sb.insert(sb.length, "}")
                } else {
                    sb.insert(0, "{\"list\":[")
                    sb.insert(sb.length, "]}")
                }
                Log.d("MicroParking", sb.toString())
                val list: MList<T> = gson.fromJson(sb.toString(), type)

                // 缓存到本地
                sharedPreferences.edit {
                    putString(listName, sb.toString())
                }

                response.list = list.list
                response.source = fromCloud
                return response
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("", e.javaClass.simpleName)
            // 网络异常，返回本地缓存数据
            if (e.javaClass.simpleName == "UnknownHostException") {
                // 本地无缓存，返回空列表
                val localDate = sharedPreferences.getString(listName, "")
                if (localDate == "") {
                    response.list = ArrayList<T>()
                    response.source = fromLocal
                    return response
                } else {
                    val list: MList<T> = gson.fromJson(localDate.toString(), type)
                    response.list = list.list
                    response.source = fromLocal
                    return response
                }

            }
        }

        // 异常，返回空列表
        response.list = ArrayList<T>()
        response.source = fromLocal
        return response
    }

    fun sendMsg(msg: String) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }

    @SuppressLint("InternalInsetResource")
    fun setStatusBarPadding(view: ViewGroup) {
        val id = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        val statusBarHeight = if (id > 0) context.resources.getDimensionPixelSize(id) else 0
        Log.d("", statusBarHeight.toString())
        view.setPadding(0, statusBarHeight, 0, 0)
    }
}